<?php
/**
 * Created by PhpStorm.
 * User: xiangfeng
 * Date: 2021/3/21
 * Time: 3:39 PM
 */

namespace app\index\controller\api;


use app\index\extend\tools\SimpleModelConnectRedis;
use think\admin\Controller;

class CronArticle extends Controller
{
    protected $redis;

    protected function initialize()
    {
        parent::initialize();
        $this->redis = SimpleModelConnectRedis::getInstance();
    }
    /**
     *异步处理
     * @throws \think\db\exception\DbException
     */
    public function updateArticleBrowseNum()
    {
        $redis = $this->redis;
        $data_len = $redis->lLen(ARTICLE_LIST);
        if ($data_len <= 0) {
            echo 0;
            sleep(10);
            die;
        }
        $b = $data_len;
        if ($data_len > 10) {
            $b = rand(11, $data_len);
        }
        $num = 0;
        for ($i = 0; $i <= $b; $i++) {
            $cache_data = $redis->rPop(ARTICLE_LIST);
            $cache_data = isset($cache_data) ? unserialize($cache_data) : [];
            $id = isset($cache_data['id']) ? $cache_data['id'] : 0;
            if ($id > 0) {
                $row = $this->app->db->name('jh_article')->where('id', $id)->inc('browse_num', rand(1,3))->update();
                if ($row) {
                    $num++;
                }

            }
        }
        echo $num;
        exit;
    }
}